package com.example.demo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.demo.pojo.WiringInfo;
import com.example.demo.service.WiringInfoService;

import java.util.ArrayList;
import java.util.List;

public class WiringInfoListener extends AnalysisEventListener<WiringInfo> {

    private static final int BATCH_COUNT = 100; // 每次批量处理的条数
    private List<WiringInfo> cachedDataList = new ArrayList<>();
    private final WiringInfoService wiringInfoService;

    // 构造函数，传入 WiringInfoService，用于保存数据
    public WiringInfoListener(WiringInfoService wiringInfoService) {
        this.wiringInfoService = wiringInfoService;
    }

    /**
     * 每解析一行调用一次
     */
    @Override
    public void invoke(WiringInfo data, AnalysisContext context) {
        cachedDataList.add(data);
        // 达到批量处理的阈值时，存储数据
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList.clear();
        }
    }

    /**
     * 全部解析完成后调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 保存剩余数据
        saveData();
    }

    /**
     * 存储数据的具体方法
     */
    private void saveData() {
        wiringInfoService.saveWiringInfo(cachedDataList);
    }
}

